package easier.app.x;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import java.util.List;
import java.util.Objects;

/**
 * 管理进程相关
 */
public class ProcessManager {

    /**
     * @param context 多进程时application多次初始化,使用该方法判断
     *
     * @return 进程名字
     */
    public static String getProcessName( Context context ) {

        ActivityManager am = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
        List< RunningAppProcessInfo > runningApps = am.getRunningAppProcesses();
        if ( runningApps == null ) {
            return null;
        }
        for ( ActivityManager.RunningAppProcessInfo procInfo : runningApps ) {
            if ( procInfo.pid == android.os.Process.myPid() ) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * @param context 多进程时application多次初始化,使用该方法判断
     *
     * @return true:app主进程
     */
    public static boolean isMainProcess( Context context ) {

        return Objects.equals( getProcessName( context ), context.getPackageName() );
    }
}